import html2canvas from 'html2canvas'
import { Ref, nextTick } from 'vue'
import { ElLoading } from 'element-plus'

/**
 * 改进版截图方法，使用临时DOM容器解决滚动区域截图问题
 * @param contentRef 内容区域的ref
 * @param snapshotRef 临时截图容器的ref
 */
export const pictureFun = async (
  contentRef: Ref<HTMLDivElement | null>,
  snapshotRef: Ref<HTMLDivElement | null>
) => {
  console.log('pictureFun')
  console.log(contentRef)
  console.log(snapshotRef)

  const loading = ElLoading.service({
    lock: true,
    text: '截图中，请稍后...',
    background: 'rgba(0, 0, 0, 0.85)'
  })

  await nextTick()

  if (!contentRef.value || !snapshotRef.value) {
    loading.close()
    return
  }

  // 克隆内容 DOM
  const clone = contentRef.value.cloneNode(true) as HTMLDivElement

  // 清理滚动和限制高度
  clone.querySelectorAll('*').forEach((el) => {
    const ele = el as HTMLElement
    ele.style.overflow = 'visible'
    ele.style.maxHeight = 'none'
    // 新增：移除row-checked类名（如果有的话）
    ele.classList.remove('row-checked')
  })

  // 设置样式让它显示出来
  snapshotRef.value.innerHTML = ''
  snapshotRef.value.appendChild(clone)
  snapshotRef.value.style.display = 'block'

  await nextTick()

  try {
    const canvas = await html2canvas(snapshotRef.value, {
      scale: 2, // 提高清晰度
      useCORS: true
    })
    const imgData = canvas.toDataURL('image/png')
    await window.electron.ipcRenderer.invoke('copy-image-to-clipboard', imgData)
    console.log('图片已复制到剪贴板')
  } catch (error) {
    console.error('截图失败:', error)
  } finally {
    snapshotRef.value.style.display = 'none'
    loading.close()
  }
}
